import datetime

from flask import Blueprint, render_template, make_response, session, request, redirect, url_for, jsonify
import re
from utils.image_captcha import ImageCode
# from utils.email_vcode import gen_email_code, send_email
from app.models.tablemodel import Users, Credit
from utils.md5 import encrypt_md5
from config.settings import RESET_FLAG  # 密码重置标志

au_bp = Blueprint('auth', __name__)


# 生成随机验证码图片
@au_bp.route('/vcode')
def vcode():
    code, bstring = ImageCode().get_vcode()
    response = make_response(bstring)
    response.headers['Content-Type'] = 'image/jpeg'
    session['vcode'] = code.lower()
    return response


#
# #邮箱验证
# @au_bp.route('/ecode', methods=['POST'])
# def ecode():
#     email = request.form.get('email')
#     if not re.match('.+@.+\\..+', email):
#         return 'email-invalid'
#     code = gen_email_code()
#     try:
#         send_email(email, code)
#         return 'send-pass'
#     except:
#         return 'send-fail'

@au_bp.route('/reg', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('login/reg.html')
    else:
        users = Users()
        username = request.form.get('username').strip()
        password = request.form.get('password').strip()
        qq = request.form.get('email').strip()  # 邮箱
        if len(password) < 5:
            return "p-invalid"  # 密码不足5位
        elif len(users.find_by_username(username)) > 0:
            return "user-repeated"
        try:  # 实现注册，同时密码md5加盐加密
            password = encrypt_md5(password)
            user = users.do_register(username, password, qq)
            session['islogin'] = 'true'
            session['userid'] = user.userid
            session['username'] = username
            session['nickname'] = user.nickname
            session['role'] = user.role
            session['avatar'] = user.avatar
        except Exception as e:
            # print(type(e))
            return "error:", type(e)
        # 更新积分表：
        credit = Credit()
        credit.insert_detail(type='用户注册', target='0', credit=50)
        return "reg-pass"


@au_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        # 获取上一个页面的URL，如果没有则使用默认首页
        prev_page = session.get('prev_page', request.referrer or url_for('index.index'))
        return render_template('login/login.html', prev_page=prev_page)
    elif request.method == 'POST':
        user = Users()
        username = request.form.get('username').strip()
        password = request.form.get('password').strip()
        vcode = request.form.get('vcode').lower().strip()
        # 校验图形验证码是否正确
        if vcode != session['vcode']:
            return 'vcode-error'
        else:
            password = encrypt_md5(password)
            result = user.find_by_username(username)
            if len(result) == 1 and result[0].password == password:
                session['islogin'] = 'true'
                session['userid'] = result[0].userid
                session['username'] = result[0].username
                session['nickname'] = result[0].nickname
                session['role'] = result[0].role
                session['avatar'] = result[0].avatar
                session['last_login_date'] = result[0].last_login_date
                # print(session['last_login_date'])
                # print(str(datetime.date.today()))
                if str(datetime.date.today()) != session['last_login_date']:
                    user.update_login_info()
                    session['last_login_date'] = str(datetime.date.today())
                    Credit().insert_detail('正常登录', 0, 1)
                # 将cookie写入浏览器
                response = make_response('login-pass')
                response.set_cookie('username', username, max_age=7 * 24 * 3600)
                response.set_cookie('password', password, max_age=7 * 24 * 3600)
                # print(response)
                return response
            else:
                return 'login-false'


@au_bp.route('/logout')
def logout():
    session.clear()  # 清空session
    # 清空cookie
    response = make_response(redirect(url_for('auth.login')))
    response.delete_cookie('username')
    response.delete_cookie('password')
    return response


@au_bp.route('/login/forgot', methods=["GET", "POST"])
def forgot_pwd():
    if request.method == 'GET':
        return render_template('login/forgot.html')
    else:
        username = request.form.get('username').strip()
        pwd = request.form.get('password').strip()
        password = encrypt_md5(pwd)
        qq = request.form.get('email').strip()
        if RESET_FLAG:
            if len(pwd) >= 5:
                result = Users().update_pwd(username, password, qq)
                if result == 'reset-pass':
                    return 'reset-success'
                else:
                    return 'reset-nouser'
            else:
                return 'pwd-less'
        else:
            return 'contact-admin'


# base.html中为配合页面静态化做的处理，在这里判断用户是否登录，根据情况返回结果，使得静态化页面中动态的添加导航栏中用户区的内容
@au_bp.route('/loginfo')
def loginfo():
    if session.get('islogin') is None:
        dic = {'logged_in': False}
        return jsonify(dic)
    else:
        dic = {}
        dic['logged_in'] = True
        dic['userid'] = session['userid']
        dic['username'] = session['username']
        dic['nickname'] = session['nickname']
        dic['role'] = session['role']
        dic['avatar'] = session['avatar']
        return jsonify(dic)
